class CarKeyboard {
	constructor(options) {
		if (!options.elem) {
			throw new Error("必须提供初始化参数");
		}

		if (!options.isValidated) {
			options.isValidated = false;
		}

		this.options = options;
		this.plateState = {
			currentPosition: 0, // 当前输入位置 (0:省份, 1:字母, 2-7:数字字母)
			plateChars: ["", "", "", "", "", "", "", ""],
			selectedProvince: "",
			keyboardVisible: false
		};
		if (this.options.elem) {
			this.init();
		}
	}

	init() {
		let html = `
            <!-- 车牌输入区域 -->
			<div class="plate-input-container">
				<div class="plate-display" id="plateDisplay">
					<span class="plate-char" id="province"></span>
					<span class="plate-char" id="letter"></span>
					<span class="plate-char" id="char1"></span>
					<span class="plate-char" id="char2"></span>
					<span class="plate-char" id="char3"></span>
					<span class="plate-char" id="char4"></span>
					<span class="plate-char" id="char5"></span>
					<span class="plate-char last-char" id="char6"></span>
				</div>
			</div>

			<!-- 虚拟键盘 -->
			<div class="virtual-keyboard">
				<!-- 关闭键盘按钮 -->
				<div class="close-keyboard">关闭键盘</div>

				<!-- 省份选择面板 -->
				<div class="keyboard-panel" id="provincesPanel">
					<!-- 省份键盘第一行 -->
					<div class="keyboard-row">
						<button class="key-btn" data-province="京">京</button>
						<button class="key-btn" data-province="津">津</button>
						<button class="key-btn" data-province="冀">冀</button>
						<button class="key-btn" data-province="晋">晋</button>
						<button class="key-btn" data-province="蒙">蒙</button>
						<button class="key-btn" data-province="辽">辽</button>
						<button class="key-btn" data-province="吉">吉</button>
						<button class="key-btn" data-province="鲁">鲁</button>
						<button class="key-btn" data-province="豫">豫</button>
						<button class="key-btn" data-province="粤">粤</button>
					</div>

					<!-- 省份键盘第二行 -->
					<div class="keyboard-row">
						<button class="key-btn" data-province="黑">黑</button>
						<button class="key-btn" data-province="沪">沪</button>
						<button class="key-btn" data-province="苏">苏</button>
						<button class="key-btn" data-province="浙">浙</button>
						<button class="key-btn" data-province="皖">皖</button>
						<button class="key-btn" data-province="闽">闽</button>
						<button class="key-btn" data-province="赣">赣</button>
						<button class="key-btn" data-province="鄂">鄂</button>
						<button class="key-btn" data-province="湘">湘</button>
						<button class="key-btn" data-province="桂">桂</button>
					</div>

					<!-- 省份键盘第三行 -->
					<div class="keyboard-row">
						<button class="key-btn" data-province="渝">渝</button>
						<button class="key-btn" data-province="川">川</button>
						<button class="key-btn" data-province="贵">贵</button>
						<button class="key-btn" data-province="云">云</button>
						<button class="key-btn" data-province="藏">藏</button>
						<button class="key-btn" data-province="陕">陕</button>
						<button class="key-btn" data-province="甘">甘</button>
						<button class="key-btn" data-province="琼">琼</button>
						<button class="key-btn" data-province="青">青</button>
						<button class="key-btn" data-province="宁">宁</button>
					</div>

					<!-- 省份键盘第四行 -->
					<div class="keyboard-row">
						<button class="key-btn" data-province="新">新</button>
						<button class="key-btn delete-btn" id="toLetter">123/ABC</button>
						<button class="key-btn delete-btn" id="deleteBtnOne">⌫</button>
					</div>
				</div>

				<!-- 字符输入面板 -->
				<div class="keyboard-panel" id="charsPanel" style="display: none">
					<!-- 数字键盘 -->
					<div class="keyboard-row">
						<button class="key-btn" data-value="0">0</button>
						<button class="key-btn" data-value="1">1</button>
						<button class="key-btn" data-value="2">2</button>
						<button class="key-btn" data-value="3">3</button>
						<button class="key-btn" data-value="4">4</button>
						<button class="key-btn" data-value="5">5</button>
						<button class="key-btn" data-value="6">6</button>
						<button class="key-btn" data-value="7">7</button>
						<button class="key-btn" data-value="8">8</button>
						<button class="key-btn" data-value="9">9</button>
					</div>

					<!-- 字母键盘 -->
					<div class="keyboard-row">
						<button class="key-btn" data-value="A">A</button>
						<button class="key-btn" data-value="B">B</button>
						<button class="key-btn" data-value="C">C</button>
						<button class="key-btn" data-value="D">D</button>
						<button class="key-btn" data-value="E">E</button>
						<button class="key-btn" data-value="F">F</button>
						<button class="key-btn" data-value="G">G</button>
						<button class="key-btn" data-value="H">H</button>
						<button class="key-btn" data-value="J">J</button>
						<button class="key-btn" data-value="K">K</button>
					</div>

					<div class="keyboard-row">
						<button class="key-btn" data-value="L">L</button>
						<button class="key-btn" data-value="M">M</button>
						<button class="key-btn" data-value="N">N</button>
						<button class="key-btn" data-value="P">P</button>
						<button class="key-btn" data-value="Q">Q</button>
						<button class="key-btn" data-value="R">R</button>
						<button class="key-btn" data-value="S">S</button>
						<button class="key-btn" data-value="T">T</button>
						<button class="key-btn" data-value="U">U</button>
						<button class="key-btn" data-value="V">V</button>
					</div>

					<div class="keyboard-row">
						<button class="key-btn" data-value="W">W</button>
						<button class="key-btn" data-value="X">X</button>
						<button class="key-btn" data-value="Y">Y</button>
						<button class="key-btn" data-value="Z">Z</button>
						<button class="key-btn special" data-value="港">港</button>
						<button class="key-btn special" data-value="澳">澳</button>
						<button class="key-btn special" data-value="挂">挂</button>
						<button class="key-btn special" data-value="领">领</button>
						<button class="key-btn special" data-value="使">使</button>
						<button class="key-btn special" data-value="学">学</button>
					</div>

					<!-- 删除按钮 -->
					<div class="keyboard-row">
						<button class="key-btn delete-btn" id="toProvinces">省/市</button>
						<button class="key-btn delete-btn" id="deleteBtnTwo">⌫ 删除</button>
					</div>
				</div>
			</div>
        `;
		$(`#${this.options.elem}`).html(html);
		this.updatePlateDisplay();
		this.bindEvent();
	}

	// 更新车牌显示
	updatePlateDisplay() {
		const self = this;
		let positions = [
			"province",
			"letter",
			"char1",
			"char2",
			"char3",
			"char4",
			"char5",
			"char6"
		];

		$.each(positions, function (index, id) {
			let $element = $("#" + id);
			$element.removeClass("active new-energy-hint");
			// 处理最后一位的特殊显示
			if (index === 7) {
				// 最后一位 char6
				if (self.plateState.plateChars[index]) {
					$element.text(self.plateState.plateChars[index]);
				} else {
					$element.text("新能源").addClass("new-energy-hint");
				}
			} else {
				$element.text(self.plateState.plateChars[index] || "");
			}
		});

		// 设置当前活动位置 - 即使全部输入完成也保持选中状态
		if (self.plateState.currentPosition < positions.length) {
			$("#" + positions[self.plateState.currentPosition]).addClass("active");
		}
	}

	// 输入字符
	inputChar(char) {
		const self = this;
		if (self.plateState.currentPosition < self.plateState.plateChars.length) {
			self.plateState.plateChars[self.plateState.currentPosition] = char;
			// 如果不是最后一个位置，则移动到下一个位置
			if (
				self.plateState.currentPosition <
				self.plateState.plateChars.length - 1
			) {
				self.plateState.currentPosition++;
			}
			self.updatePlateDisplay();
		}
	}

	// 删除字符
	deleteChar() {
		const self = this;
		self.plateState.plateChars[self.plateState.currentPosition] = "";
		// 如果删除的是省份位置，清空省份信息
		if (self.plateState.currentPosition === 0) {
			self.plateState.selectedProvince = "";
		}

		if (
			self.plateState.currentPosition === 1 ||
			self.plateState.currentPosition === 0
		) {
			self.switchTab("provinces"); // 省份位置显示省市键盘
		} else {
			self.switchTab("chars"); // 省份位置显示字符键盘
		}

		// 如果当前位置不是第一个位置且当前位置为空，向前移动光标
		if (
			self.plateState.currentPosition > 0 &&
			self.plateState.plateChars[self.plateState.currentPosition] === ""
		) {
			// 查找前一个非空位置
			let prevPosition = self.plateState.currentPosition - 1;
			while (
				prevPosition >= 0 &&
				self.plateState.plateChars[prevPosition] === ""
			) {
				prevPosition--;
			}
			self.plateState.currentPosition = Math.max(0, prevPosition);
		}

		self.updatePlateDisplay();
	}

	// 展示键盘
	showKeyboard() {
		const self = this;
		if (!self.plateState.keyboardVisible) {
			$(`#${self.options.elem}`).find(".virtual-keyboard").addClass("show");
			self.plateState.keyboardVisible = true;
			// 根据当前输入位置自动选择键盘类型
			if (self.plateState.currentPosition === 0) {
				self.switchTab("provinces"); // 省份位置显示省市键盘
			} else {
				self.switchTab("chars"); // 其他位置显示字符键盘
			}
		}
	}

	// 隐藏键盘
	hideKeyboard() {
		const self = this;
		if (self.plateState.keyboardVisible) {
			$(`#${self.options.elem}`).find(".virtual-keyboard").removeClass("show");
			self.plateState.keyboardVisible = false;
		}
	}

	// 键盘切换
	switchTab(tabName) {
		const self = this;
		// 切换面板显示
		$(`#${self.options.elem}`)
			.find("#charsPanel")
			.css("display", tabName === "chars" ? "block" : "none");
		$(`#${self.options.elem}`)
			.find("#provincesPanel")
			.css("display", tabName === "provinces" ? "block" : "none");
	}

	// 绑定函数
	bindEvent() {
		const self = this;
		// 键盘事件
		$(`#${self.options.elem}`).on("click", ".key-btn", function () {
			const value = $(this).attr("data-value");
			const province = $(this).attr("data-province");
			if (province) {
				// 省份选择
				self.plateState.selectedProvince = province;
				self.plateState.plateChars[0] = province;
				self.plateState.currentPosition = 1; // 选择省份后跳到字母位置
				self.updatePlateDisplay();
				self.switchTab("chars"); // 自动切换到字符输入
			} else if (value && !$(this).hasClass("delete-btn")) {
				// 字符输入
				self.inputChar(value);
			}
		});

		// 删除事件
		$(`#${self.options.elem}`).on("click", "#deleteBtnOne", function () {
			self.deleteChar();
		});
		$(`#${self.options.elem}`).on("click", "#deleteBtnTwo", function () {
			self.deleteChar();
		});

		// 省份切换
		$(`#${self.options.elem}`).on("click", "#toProvinces", function () {
			self.switchTab("provinces");
		});

		// 字母切换
		$(`#${self.options.elem}`).on("click", "#toLetter", function () {
			self.switchTab("chars");
		});

		// 点击展示键盘
		// $(`#${self.options.elem}`).on("click", "#plateDisplay", function () {
		// 	self.showKeyboard();
		// });

		// 点击第一个输入框
		$(`#${self.options.elem}`).on("click", "#province", function () {
			self.plateState.currentPosition = 0;
			self.updatePlateDisplay();
			self.showKeyboard();
			self.switchTab("provinces"); // 显示省市键盘
		});

		// 点击后续输入框
		$(`#${self.options.elem}`).on(
			"click",
			"#letter, #char1, #char2, #char3, #char4, #char5, #char6",
			function () {
				// 获取当前点击的输入框位置
				let positions = [
					"province",
					"letter",
					"char1",
					"char2",
					"char3",
					"char4",
					"char5",
					"char6"
				];
				let clickedId = $(this).attr("id");
				let newPosition = positions.indexOf(clickedId);

				if (newPosition !== -1) {
					self.plateState.currentPosition = newPosition;
					self.updatePlateDisplay();
					self.showKeyboard();
					self.switchTab("chars"); // 显示字符键盘
				}
			}
		);

		// 关闭键盘
		$(`#${self.options.elem}`).on("click", ".close-keyboard", function () {
			self.hideKeyboard();
		});
	}

	// 清空车牌
	clearPlate() {
		const self = this;
		self.plateState.plateChars = ["", "", "", "", "", "", "", ""];
		self.plateState.currentPosition = 0;
		self.plateState.selectedProvince = "";
		self.updatePlateDisplay();
		self.hideKeyboard();
	}
	// 获取车牌信息
	getPlate() {
		const self = this;
		let plate = self.plateState.plateChars.join("");
		if (self.options.isValidated) {
			// 车牌号正则表达式
			// 普通车牌：粤B12345 / 粤BD12345
			let normalPlateRegex =
				/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-Z0-9]{4}[A-Z0-9挂学警港澳]$/;

			// 新能源车牌：粤B12345D / 粤BD12345F
			let newEnergyPlateRegex =
				/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-Z0-9]{5}[A-Z0-9挂学警港澳]$/;

			if (plate.length < 7) {
				return {
					isValidated: false,
					plate: plate
				};
			}

			if (normalPlateRegex.test(plate) || newEnergyPlateRegex.test(plate)) {
				return {
					isValidated: true,
					plate: plate
				};
			} else {
				return {
					isValidated: false,
					plate: plate
				};
			}
		} else {
			return plate;
		}
	}
	// 回显函数
	setPlate(plateNumber) {
		const self = this;
		if (!plateNumber || typeof plateNumber !== "string") {
			throw new Error("请提供有效的车牌号");
		}

		self.clearPlate();

		let chars = plateNumber.split("");

		if (chars.length < 7 || chars.length > 8) {
			throw new Error("车牌号长度不正确，应为7-8位");
		}

		// 填充状态
		for (
			let i = 0;
			i < chars.length && i < self.plateState.plateChars.length;
			i++
		) {
			self.plateState.plateChars[i] = chars[i];
		}

		// 设置省份
		if (chars.length > 0) {
			self.plateState.selectedProvince = chars[0];
		}

		// 设置当前位置为最后一个有效字符的下一位（用于继续输入）
		self.plateState.currentPosition = Math.min(
			chars.length,
			self.plateState.plateChars.length - 1
		);
		// 更新显示
		self.updatePlateDisplay();
		// 展示键盘
		self.showKeyboard();
	}

	// 销毁函数
	destroy() {
		const self = this;
		// 移除所有事件监听器
		$(`#${self.options.elem}`).off();
		// 清空DOM内容
		$(`#${self.options.elem}`).empty();
		// 重置状态
		self.plateState = {
			currentPosition: 0,
			plateChars: ["", "", "", "", "", "", "", ""],
			selectedProvince: "",
			keyboardVisible: false
		};
		// 清空选项
		self.options = null;
	}
}